﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ExtendLib.Helper;
using Ivony.Fluent;

namespace SmsBomb
{
    public partial class CheckIp : Form
    {
        private List<string> _ipList { get; set; }
        private string _keyWord { get; set; }
        public CheckIp()
        {
            InitializeComponent();
        }

        #region 事件
        /// <summary>
        /// 一键导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnImport_Click(object sender, EventArgs e)
        {
            _ipList = new List<string>();
            //定义一个文件打开控件
            OpenFileDialog ofd = new OpenFileDialog();
            //设置打开对话框的初始目录，默认目录为exe运行文件所在的路径
            ofd.InitialDirectory = Application.StartupPath;
            //设置打开对话框的标题
            ofd.Title = "请选择要打开的文件";
            //设置打开对话框可以多选
            ofd.Multiselect = true;
            //设置对话框打开的文件类型
            ofd.Filter = "文本文件|*.txt";
            //设置文件对话框当前选定的筛选器的索引
            ofd.FilterIndex = 2;
            //设置对话框是否记忆之前打开的目录
            ofd.RestoreDirectory = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //获取用户选择的文件完整路径
                string filePath = ofd.FileName;
                //获取对话框中所选文件的文件名和扩展名，文件名不包括路径
                //string fileName = ofd.SafeFileName;
                using (FileStream fsRead = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read))
                {
                    //定义二进制数组
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    //从流中读取字节
                    int r = fsRead.Read(buffer, 0, buffer.Length);
                    string content = Encoding.Default.GetString(buffer, 0, r);
                    var list = content.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    if (list.Any() == false)
                    {
                        return;
                    }
                    foreach (string ipItem in list)
                    {
                        _ipList.Add(ipItem);
                        listIp.Items.Add(ipItem);
                    }
                }
            }
        }

        /// <summary>
        /// 开始验证
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCheck_Click(object sender, EventArgs e)
        {
            string url = this.txtUrl.Text,
                key = this.txtKeyWord.Text;
            if (url.IsNullOrEmpty() || key.IsNullOrEmpty())
                return;
            _keyWord = key;
            Thread th = new Thread(delegate()
            {
                ParallelLoopResult loopResult = Parallel.ForEach(_ipList, ActionBtSearch);
            }) { IsBackground = true };
            th.Start();

        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            string checkSuccess = listResult.Items.Cast<object>().Aggregate("", (current, item) => current + (item + "\r\n"));
            //定义一个文件打开控件
            SaveFileDialog ofd = new SaveFileDialog();
            //设置打开对话框的初始目录，默认目录为exe运行文件所在的路径
            ofd.InitialDirectory = Application.StartupPath;
            //设置打开对话框的标题
            ofd.Title = "请选择要打开的文件";
            //设置对话框是否记忆之前打开的目录
            ofd.RestoreDirectory = true;
            ofd.Filter = "文本文件|*.txt";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //获取用户选择的文件完整路径
                string filePath = ofd.FileName;
                File.WriteAllText(filePath, checkSuccess);
            }
        }
        /// <summary>
        /// 一键导入数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnImportData_Click(object sender, EventArgs e)
        {
            List<string> list= (from object item in listResult.Items select item.ToString()).ToList();
            bool r= ControlHelper.SaveProxyIp(list);
            if (r)
            {
                MessageBox.Show("导入成功！开始干活吧！");
            }
        }
        #endregion

        #region 跨线程委托
        /// <summary>
        ///  Parallel 委托类 并发运行所有
        /// </summary>
        /// <param name="item"></param>
        /// <param name="state"></param>
        private void ActionBtSearch(string item, ParallelLoopState state)
        {
            try
            {
                var temp = item.Split(':');
                HttpRequestItem hri = new HttpRequestItem
                {
                    Url = txtUrl.Text,
                    ProxyIp = temp[0],
                    ProxyPort = int.Parse(temp[1]),
                    TimeOut = 10000
                };
                var rd = HttpHelper.GetHtml(hri);
                if (rd.DataInfo.IndexOf(_keyWord, StringComparison.CurrentCultureIgnoreCase) >= 0)
                {
                    SetText(item);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WirteLog(string.Format("线程:{0}正在访问URL:{1},异常：{2}", Thread.CurrentThread.ManagedThreadId, item,
                    ex.Message));
            }
            finally
            {
                Remove(item);
            }
        }
        delegate void SetTextCallback(string text);
        /// <summary>
        /// 跨线程设置
        /// </summary>
        /// <param name="text"></param>
        public void SetText(string text)
        {
            if (this.listResult.InvokeRequired)
            {
                SetTextCallback d = SetText;
                this.Invoke(d, text);
            }
            else
            {
                this.listResult.Items.Add(text);
            }
        }

        delegate void RemoveItem(string item);
        /// <summary>
        /// 跨线程移除
        /// </summary>
        /// <param name="item"></param>
        public void Remove(string item)
        {
            if (this.listIp.InvokeRequired)
            {
                RemoveItem d = Remove;
                this.Invoke(d, item);
            }
            else
            {
                this.listIp.Items.Remove(item);
            }
        } 
        #endregion

       
      
    }
}
